import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class MessageNoticeService {
  //://github.com/fleckandreas/ng-sse-example/blob/master/src/app/services/backend.service.ts
  private _eventSource!: EventSource;
  private _subscribed: boolean = false;
  private  restRequestURI: string;
  private messageNoticeSubject = new Subject<number>();
  /**
   * 未读消息数量服务
   * @param messageNoticeService 
   * @param memberStorage 
   */
  constructor() { 
    console.log('[MessageNotice-SRV]constructor start');
    this.restRequestURI = environment.restURI + '/letter';
  }

  public start(memberId:number) {
    console.log('[MessageNotice-SRV]query start');
    if (!this._subscribed && memberId>0) {
      const url: string = this.restRequestURI + '/inbox/' + memberId + '/notice';
      this._eventSource = new EventSource(url);

      this._eventSource.addEventListener('UnReadMessages', (message: any) => {
        this.messageNoticeSubject.next(message.data);
      });
      this._eventSource.addEventListener('error', (message: any) => {
        this.messageNoticeSubject.error(message);
      });
      this._subscribed = true;
    }
  }

  public query(): Observable<number> {
    return this.messageNoticeSubject.asObservable();
  }

  public disconnect() {
    if (this._subscribed) {
      this._eventSource.close();
      this._subscribed = false;
    }
  }
}
